package com.english.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;

/**
 * 微信支付直接测试工具
 */
public class WechatPayDirectTester {
    
    public static void main(String[] args) {
        System.out.println("=== 直接测试微信支付统一下单接口 ===");
        testUnifiedOrder();
    }
    
    public static void testUnifiedOrder() {
        try {
            // 1. 构建测试参数
            Map<String, String> params = new TreeMap<>();
            params.put("appid", "wx2f9ca3ee9556234f");
            params.put("mch_id", "1724666825");
            params.put("nonce_str", "test" + System.currentTimeMillis());
            params.put("body", "Test Payment");  // 使用英文避免编码问题
            params.put("out_trade_no", "TEST" + System.currentTimeMillis());
            params.put("total_fee", "1");  // 1分
            params.put("spbill_create_ip", "127.0.0.1");
            params.put("notify_url", "https://test.com/notify");
            params.put("trade_type", "JSAPI");
            params.put("openid", "opMFNvowB-lDGIOGm7cCewHVRTG4");
            params.put("sign_type", "MD5");
            
            // 2. 生成签名
            String apiKey = "18308909937or18970222333Oscar168";
            String sign = generateSign(params, apiKey);
            params.put("sign", sign);
            
            // 3. 构建XML请求
            String xmlRequest = buildXml(params);
            System.out.println("请求XML:");
            System.out.println(xmlRequest);
            
            // 4. 发送HTTP请求
            String response = sendHttpRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", xmlRequest);
            System.out.println("\n微信响应:");
            System.out.println(response);
            
            // 5. 解析响应
            parseResponse(response);
            
        } catch (Exception e) {
            System.err.println("测试失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static String generateSign(Map<String, String> params, String apiKey) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (entry.getValue() != null && !entry.getValue().isEmpty() && !"sign".equals(entry.getKey())) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        sb.append("key=").append(apiKey);
        
        String stringToSign = sb.toString();
        System.out.println("待签名字符串: " + stringToSign);
        
        return md5(stringToSign).toUpperCase();
    }
    
    private static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(input.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte b : array) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5失败", e);
        }
    }
    
    private static String buildXml(Map<String, String> params) {
        StringBuilder xml = new StringBuilder("<xml>");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            xml.append("<").append(entry.getKey()).append("><![CDATA[")
               .append(entry.getValue()).append("]]></").append(entry.getKey()).append(">");
        }
        xml.append("</xml>");
        return xml.toString();
    }
    
    private static String sendHttpRequest(String urlString, String xmlData) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        
        // 设置请求属性
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/xml; charset=UTF-8");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        
        // 发送请求数据
        try (OutputStream os = conn.getOutputStream()) {
            os.write(xmlData.getBytes("UTF-8"));
            os.flush();
        }
        
        // 读取响应
        int responseCode = conn.getResponseCode();
        System.out.println("HTTP响应码: " + responseCode);
        
        BufferedReader reader;
        if (responseCode >= 200 && responseCode < 300) {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        } else {
            reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
        }
        
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        
        return response.toString();
    }
    
    private static void parseResponse(String xmlResponse) {
        System.out.println("\n=== 响应分析 ===");
        
        // 简单解析关键字段
        if (xmlResponse.contains("<return_code>")) {
            String returnCode = extractValue(xmlResponse, "return_code");
            System.out.println("return_code: " + returnCode);
        }
        
        if (xmlResponse.contains("<return_msg>")) {
            String returnMsg = extractValue(xmlResponse, "return_msg");
            System.out.println("return_msg: " + returnMsg);
        }
        
        if (xmlResponse.contains("<result_code>")) {
            String resultCode = extractValue(xmlResponse, "result_code");
            System.out.println("result_code: " + resultCode);
        }
        
        if (xmlResponse.contains("<err_code>")) {
            String errCode = extractValue(xmlResponse, "err_code");
            System.out.println("err_code: " + errCode);
        }
        
        if (xmlResponse.contains("<err_code_des>")) {
            String errCodeDes = extractValue(xmlResponse, "err_code_des");
            System.out.println("err_code_des: " + errCodeDes);
        }
    }
    
    private static String extractValue(String xml, String tagName) {
        String startTag = "<" + tagName + "><![CDATA[";
        String endTag = "]]></" + tagName + ">";
        
        int startIndex = xml.indexOf(startTag);
        if (startIndex == -1) {
            // 尝试不带CDATA的格式
            startTag = "<" + tagName + ">";
            endTag = "</" + tagName + ">";
            startIndex = xml.indexOf(startTag);
        }
        
        if (startIndex != -1) {
            startIndex += startTag.length();
            int endIndex = xml.indexOf(endTag, startIndex);
            if (endIndex != -1) {
                return xml.substring(startIndex, endIndex);
            }
        }
        
        return "未找到";
    }
} 